﻿using System.ComponentModel.DataAnnotations.Schema;
using Core.Domain.Enums;
using Core.Domain.Events;

namespace Core.Domain.Entities;

#nullable disable

/// <summary>
/// 角色权限表
/// </summary>
[Table("RolePermissions")]
public class RolePermission : AuditableEntity
{
    /* 1.1 数据：全部私有 set */
    public Guid RoleId { get; private set; }
    public Guid PermissionId { get; private set; }
    public AccessState AccessState { get; private set; }

    public virtual Role Role { get; private set; }
    public virtual Permission Permission { get; private set; }
    /* 1.2 构造保护不变式 */
    private RolePermission() { } // EF

    public RolePermission(Role role, Permission permission, AccessState state = AccessState.Unspecified)
    {
        RoleId = role.Id;
        PermissionId = permission.Id;
        AccessState = state;
        QueueDomainEvent(new RolePermissionCreated(role.Id, permission.Id, state));
    }

    public static RolePermission Create(Role role, Permission permission, AccessState state = AccessState.Unspecified)
    {
        if (role is null || permission is null)
            throw new ArgumentException("角色或权限不能为空");

        return new RolePermission(role, permission, state);
    }

    /* 业务行为：切换授权状态 */
    public void Allow()
    {
        if (AccessState == AccessState.Allow) return;
        AccessState = AccessState.Allow;
        QueueDomainEvent(new RolePermissionStateChanged(RoleId, PermissionId, AccessState));
    }

    public void Deny()
    {
        if (AccessState == AccessState.Deny) return;
        AccessState = AccessState.Deny;
        QueueDomainEvent(new RolePermissionStateChanged(RoleId, PermissionId, AccessState));
    }

    public void Reset()
    {
        if (AccessState == AccessState.Unspecified) return;
        AccessState = AccessState.Unspecified;
        QueueDomainEvent(new RolePermissionStateChanged(RoleId, PermissionId, AccessState));
    }
}
